import axios from 'axios';

import { BASE_URL, TIMEOUT } from "./config";
import qs from 'qs'
import { message } from 'antd';
import { login } from '../common/login'
const instance = axios.create({
  baseURL: BASE_URL,
  timeout: TIMEOUT
});

instance.interceptors.request.use(config => {
  // 1.发送网络请求时, 在界面的中间位置显示Loading的组件

  // 2.某一些请求要求用户必须携带token, 如果没有携带, 那么直接跳转到登录页面
  // ctx.method = 'POST'
  config.headers = {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    Authorization: readCookie('userCode') || '',
  }
  if (config.type === 'upload') {
    config.baseURL = ''
    config.headers = {
      'Content-Type': 'multipart/form-data; boundary=' + new Date().getTime(),
      Authorization: readCookie('userCode') || '',
    }
  } else {
    config.baseURL = BASE_URL
  }
  if (config.method === 'post') {
    if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8') {
      config.data = qs.stringify(config.data, {
        allowDots: true,
      })
    }



  }
  return config;
}, err => {

});

instance.interceptors.response.use(res => {
  const { code, content } = res.data
  switch (code) {
    case 200:
      return res.data;
    case 400:
      message.error(content || '请刷新后重新尝试!')
      return Promise.reject(content)
    case 11005:
      message.error(content || '请刷新后重新尝试!')
      return Promise.reject(content)
    case 10400:
      // message.error(content || '请刷新后重新尝试!')
      login()
      return Promise.reject(content)
    default:
      message.error(content || '请刷新后重新尝试!')
      return Promise.reject(content)
  }

}, err => {
  console.log(err, '错误')
  if (err && err.response) {
    switch (err.response.status) {
      case 500:
        console.log("请求错误");
        break;
      case 401:
        console.log("未授权访问");
        break;
      default:
        console.log("其他错误信息");
    }
  }
  return err;
});
function readCookie(cookieName) {
  var theCookie = '' + document.cookie;
  var ind = theCookie.indexOf(cookieName);
  if (ind === -1 || cookieName === '') return '';
  var ind1 = theCookie.indexOf(';', ind);
  if (ind1 === -1) ind1 = theCookie.length;
  /*读取Cookie值*/
  return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}

export default instance;

